package com.biscuit.page.basicservice.filter;

import com.alibaba.fastjson.JSON;
import com.biscuit.page.basicservice.design.flow_limit.strategy.FlowLimitHandlerStrategy;
import com.biscuit.page.basicservice.model.enums.BaseResponseEnum;
import com.biscuit.page.basicservice.utils.BaseResponseUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author biscuit
 * @create 2024年07月29日 14:59
 */
@Order(value = 0)
@WebFilter(urlPatterns = "/*")
@Component
public class FlowLimitFilter implements Filter {

    @Resource
    FlowLimitHandlerStrategy flowLimitHandlerStrategy;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {

            // 判断是否开启了限流测试，未开启则之间放行
            // if (Objects.isNull(this.flowLimitHandlerStrategy)) {
            //     filterChain.doFilter(servletRequest, servletResponse);
            //     return;
            // }

            // 根据限流策略调用策略对应的限流逻辑，获取是否可以放行的结果
            boolean isPass = this.flowLimitHandlerStrategy.attempt();

            // 根据放行结果进行不同的处理
            if (isPass) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                httpServletResponse.setContentType("application/json;charset=utf-8");
                httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                httpServletResponse.getWriter().write(JSON.toJSONString(BaseResponseUtil.fail(BaseResponseEnum.ERROR_SERVICE, "服务器繁忙，请稍后重试")));
            }
        } catch (Exception e) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
